package com.hongmeng.operater.service.impl;

import com.aliyun.oss.OSSClient;
import com.hongmeng.common.core.domain.AjaxResult;
import com.hongmeng.common.utils.file.ALiYunUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.hongmeng.operater.mapper.HmFileMapper;
import com.hongmeng.operater.domain.HmFile;
import com.hongmeng.operater.service.IHmFileService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 文件Service业务层处理
 * 
 * @author hongmeng
 * @date 2020-12-21
 */
@Service
@Slf4j
public class HmFileServiceImpl implements IHmFileService
{

    @Value("${bucket.bucketName}")
    private String bucketName;

    @Value("${bucket.diskName_tmp}")
    private String diskNameTmp;

    @Autowired
    private HmFileMapper hmFileMapper;

    @Autowired
    private HttpServletResponse response;

    @Override
    public AjaxResult selectFileInfo(Integer id) {
        return AjaxResult.success(hmFileMapper.selectHmFileById(id));
    }

    @Override
    public void downloadFile(Integer fileId) {
        log.info("文件下载,传入文件ID为{}",fileId);
        OSSClient client = ALiYunUploadUtils.getOSSClient();
        HmFile tmpFile = hmFileMapper.selectHmFileById(fileId);
        if (tmpFile==null){
            log.info("找不到文件id为{}的文件",fileId);
            return;
        }
        String fileName = tmpFile.getFileUrl().substring(tmpFile.getFileUrl().lastIndexOf("/")+1,tmpFile.getFileUrl().length());
        InputStream inputStream = ALiYunUploadUtils.getOSS2InputStream(client,bucketName,diskNameTmp,fileName);
        try {
            response.setContentType(tmpFile.getContentType());
            response.addHeader("Content-Disposition", "filename="+URLEncoder.encode(tmpFile.getFileName(), "UTF-8"));
            OutputStream out = response.getOutputStream();
            //输出文件
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = inputStream.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.close();
        }catch (IOException e){
            log.error(e.getMessage(), e);
        }finally {
            try {
                inputStream.close();
            }catch (IOException e){

            }
        }
    }
}
